<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion"></i>后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/sys-admin/product/category' }">商品类别管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品类别</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">

      <el-form-item label="父级类别" prop="parentId">
        <span class="demonstration"></span>
        <el-cascader
            style="width: 100%;"
            placeholder="请选择父级类别，如不选择，则表示无父级类别"
            :props="{ checkStrictly: true }"
            v-model="ruleForm.parentId"
            :options="categoryTreeOptions"></el-cascader>
        <span>如果父级类别列表不准确，请点击 <a class="simple-link" href="#" @click="loadCategoryTree">这里</a> 刷新。</span>
      </el-form-item>

      <el-form-item label="名称" prop="name">
        <el-input v-model="ruleForm.name"></el-input>
      </el-form-item>

      <el-form-item label="关键词" prop="keywords">
        <el-input v-model="ruleForm.keywords"></el-input>
      </el-form-item>

      <el-form-item label="排序序号" prop="sort">
        <el-input v-model="ruleForm.sort"></el-input>
      </el-form-item>

      <el-form-item label="图标" prop="icon">
        <el-input v-model="ruleForm.icon"></el-input>
      </el-form-item>

      <el-form-item label="是否启用" prop="enable">
        <el-input v-model="ruleForm.enable"></el-input>
      </el-form-item>

      <el-form-item label="是否展示" prop="isDisplay">
        <el-input v-model="ruleForm.isDisplay"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">添加</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
        <el-button type="warning" @click="$router.push('/sys-admin/product/category')">返回列表</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
let localJwt = localStorage.getItem('localJwt');
import axios from "axios";

export default {
  data() {
    return {
      categoryTreeOptions : [],
      ruleForm: {
        name: '商品类别1',
        parentId: '0',
        keywords: '无',
        sort: '99',
        icon: '无',
        enable: '1',
        isDisplay: '1'
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 1, max: 25, message: '长度在 1 到 25 个字符', trigger: 'blur' }
        ],
        parentId: [
          { required: true, message: '请输入父级id', trigger: 'blur' }
        ],
        keywords: [
          { required: true, message: '请输入关键词', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请输入排序序号', trigger: 'blur' },
          { pattern: /^(\d{1}|[1-9]{1}[0-9]{1})$/, message: '排序序号必须是0~99之间的整数', trigger: 'blur' }
        ],
        icon: [
          { required: true, message: '请输入图标', trigger: 'blur' }
        ],
        enable: [
          { required: true, message: '请输入是否禁用', trigger: 'blur' }
        ],
        isDisplay: [
          { required: true, message: '请输入是否展示', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      // 由于formData里面记录了从父级到自己的所有parentId，我们只需要pop()删除并返回数组的最后一个元素
      if (Array.isArray(this.ruleForm.parentId)) {
        this.ruleForm.parentId = this.ruleForm.parentId.pop();
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = "http://localhost:8080/category/add-new";
          let formData = this.qs.stringify(this.ruleForm);
          console.log(formData);
          axios
              .create({
                'headers': {
                  'Authorization': localJwt
                }
              })
              .post(url, formData).then((response) => {
            let jsonResult = response.data;
            if (jsonResult.state === 200) {
              this.$message({
                message: '添加商品类别成功！',
                type: 'success'
              });
              this.resetForm(formName);
            } else {
              this.$alert(jsonResult.message, '错误', {
                confirmButtonText: '确定',
                callback: action => {
                }
              });
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    loadCategoryTree() {
      let url = "http://localhost:8080/category/tree";
      axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          this.categoryTreeOptions = jsonResult.data;
          // unshift() 方法可向数组的开头添加一个或更多元素，并返回新的长度
          this.categoryTreeOptions.unshift({
            value: 0,
            label: '无父级类别'
          });
          // 将parentId默认值设置为0即为一级类别（后续选择类别的时候会改变这个值）
          this.ruleForm.parentId = "0";
        }
      });
    }
  },
  mounted() {
    this.loadCategoryTree();
  }
}
</script>
